package com.yh.correct.controller;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yh.common.utils.ExcelUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.yh.correct.model.Condition;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.LeavePersonnel;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.RuleBreak;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IJudicialDeptmentService;
import com.yh.correct.service.ILeavePersonnelService;

/**
 * 
 * 外出请假条控制层
 * @author swj
 *
 */

@RestController
@RequestMapping("/leave")
public class LeavePersonnelController {

	/**
	 * 日志记录
	 */
	private static Logger logger=LogManager.getLogger(LeavePersonnelController.class);
	/**
	 * 注入外出请假登记服务
	 */
	@Autowired
	private ILeavePersonnelService leavepersonnelservice;
	
	/**
	 * 注入司法所服务层接口
	 */
	@Autowired
	public IJudicialDeptmentService jud;
	
	 /**
	 * 注入矫正人员服务层接口
	 */
	@Autowired
	public ICorrectedPersonService cor;
	
	/**
	 * 显示请假登记页面
	 * @return
	 */
	@RequestMapping(value="/show")
	public ModelAndView toShow(){
		ModelAndView mv=new ModelAndView("/supervision/leave");
		
		return mv;
	}
	
	/**
	 * 增加外出请假登记信息
	 * @param leavepersonnel
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="/add")
	public ResultData addLeavePersonnel(LeavePersonnel leavepersonnel,String jid,String pid,String dates,String startdates,String enddates) throws ParseException{
		int i=0;
		leavepersonnel.setJid(Integer.parseInt(String.valueOf(jid)));
		leavepersonnel.setPid(Integer.parseInt(String.valueOf(pid)));
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
		leavepersonnel.setDate(sdf.parse(dates));
		leavepersonnel.setEnddate(sdf.parse(enddates));
		leavepersonnel.setStartdate(sdf.parse(startdates));
		try {
			i=leavepersonnelservice.addLeavePersonnel(leavepersonnel);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("增加成功");
		}else{
			rd.setCode(-1);
			rd.setMessage("增加失败");
		}
		logger.debug("增加外出请假登记+LeavePersonnelController");
		return rd;
		
	}
	
	
	/**
	 * 删除外出请假登记信息
	 * @param leavepersonnel
	 * @return
	 */
	@RequestMapping(value="/del")
	public ResultData delLeavePersonnel(LeavePersonnel leavepersonnel){
	    int i=0;
		try {
			 i=leavepersonnelservice.delLeavePersonnel(leavepersonnel);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    ResultData rd=new ResultData();
	    if(i>0){
	    	rd.setCode(0);
	    	rd.setMessage("删除成功");
	    }else{
	    	rd.setCode(-1);
	    	rd.setMessage("删除失败");
	    }
		return rd;	
	}

	/**
	 * 批量删除请假信息
	 * @param list
	 * @return
     */
	@RequestMapping("/deleteBatch")
	public ResultData deleteBatch(@RequestParam("ids[]") List<Integer> list){
		ResultData rd = new ResultData();
		int i = 0;
		try {
			i = leavepersonnelservice.deleteBatch(list);
			if(i>0){
				rd.setCode(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rd;
	}
	/**
	 * 修改外出请假登记信息
	 * @param leavepersonnel
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/edit")
	public ResultData editLeavePersonnel(LeavePersonnel leavepersonnel,String dates,String startdates,String enddates) throws Exception{
		int i=0;
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
		leavepersonnel.setDate(sdf.parse(dates));
		leavepersonnel.setEnddate(sdf.parse(enddates));
		leavepersonnel.setStartdate(sdf.parse(startdates));
		logger.info("修改外出请假登记记录id="+leavepersonnel.toString());
		i=leavepersonnelservice.editLeavePersonnel(leavepersonnel);
		 ResultData rd=new ResultData();
		    if(i>0){
		    	rd.setCode(0);
		    	rd.setMessage("修改成功");
		    }else{
		    	rd.setCode(-1);
		    	rd.setMessage("修改失败");
		    }
			return rd;	
	}
	
	
	
	/**
	 * 查询单条外出请假登记信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/getidleave")
	public ResultData getIdLeavePersonnel(int id){
		logger.debug(id);
		LeavePersonnel lp=new LeavePersonnel();
		lp.setId(id);
		Map map=null;
		try {
			map=leavepersonnelservice.getIdLeavePersonnel(lp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd=new ResultData();
		if(map!=null){
			rd.setCode(0);
			rd.setMessage("查询单个信息成功");
		}else{
			rd.setCode(-1);
			rd.setMessage("查询单个信息失败");
		}
		return null;
		
	}

	/**
	 * 模糊查询 查询条件（请假编号,矫正单位编号，服刑人员编号）
	 * @param pageSize
	 * @param pageNum
	 * @param id
	 * @param jid
	 * @param startdate
	 * @param enddate
     * @return
     * @throws Exception
     */
	@RequestMapping(value="/getlike")
	public ResultData getLikeLeavePersonnel(int pageSize,int pageNum, String id, String jid,String startdate,String enddate) throws Exception{
		Map<String,Object> m=new HashMap<String,Object>();
//		如果矫正人员和司法所的id为空则置为零，sql语句会进行全查询
		Integer jid1=0;
		if(jid!=null&&!"".equals(jid)){
			jid1=Integer.parseInt(String.valueOf(jid));
		}
		Integer id1=0;
		if(id!=null&&!"".equals(id)){
			id1=Integer.parseInt(String.valueOf(id));
		}
		m.put("pageSize",pageSize);
		m.put("pageNum",pageNum);
		m.put("jid", jid1);
		m.put("id", id1);
		m.put("startdate", startdate);
		m.put("enddate", enddate);
		Page page=leavepersonnelservice.getLikeLeavePersonnel(m);
		logger.info(page);
	    ResultData rd=new ResultData();
	    if(page!=null){
	    	List<Object> lp=new ArrayList();
	    	lp.add(page);
	    	rd.setCode(0);
	    	rd.setMessage("查询成功");
	    	rd.setData(lp);
	    }else{
	    	rd.setCode(-1);
	    	rd.setMessage("查询失败");
	    }
	    
		return rd;
	}

	/**
	 * 增加窗口跳转
	 * 
	 * @return
	 */
	@RequestMapping(value="/addskip")
	public ModelAndView addSkip(){
		return new ModelAndView("supervision/leave_add");
		
	}
	
	/**
	 * 修改页面跳转
	 * @return
	 */
	@RequestMapping(value="/editskip")
	public ModelAndView editSkip(){
		return new ModelAndView("supervision/leave_edit");
		
	}
	
	
	/**
	 * 矫正单位下拉框显示
	 * @return
	 */
	@RequestMapping(value="/jselect")
	public List<Object> jShowSelect(){
		List<Object> list=jud.listJudicialDeptments();
		for (Object object : list) {
			logger.info("ja列表"+object.toString());
		}
		return list;
		
	}
	
	/**
	 * 矫正人员下拉框显示
	 * @return
	 */
	@RequestMapping(value="/pselect")
	public List pShowSelect(){
		List<CorrectedPerson> list=null;
		try {
			list = cor.findCorrectedPerson();
			for (Object object : list) {
				logger.info("ps列表"+object.toString());
			}

		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return list;	
	}
	
	
	
	/**
	 * 获取外出请假登记详情
	 * 
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/detail")
	public ModelAndView getDetail(HttpServletRequest request, LeavePersonnel leavepersonnel, String sort) throws Exception {	
		Map<String, Object> m = leavepersonnelservice.getLeavePersonnelById(leavepersonnel);
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("details", m);
		logger.info("查看详情" + m.toString());
		if ("look".equals(sort)) {
			return new ModelAndView("supervision/leave_look", rsMap);
		}
		return new ModelAndView("supervision/leave_edit", rsMap);
	}

	/**
	 * 导出Excle
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/excel")
	public String outExcle(HttpServletRequest request, HttpServletResponse response, int[] ids){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
//				传处遇等级ids非空时批量导出所选项，否则导出所有
			if (ids != null && ids.length>0) {
				for (int id : ids) {
					LeavePersonnel leavePersonnel=new LeavePersonnel();
					leavePersonnel.setId(id);
					Map<String, Object> map = leavepersonnelservice.getIdLeavePersonnel(leavePersonnel);
					list.add(map);
				}
			} else {
				list = leavepersonnelservice.getAllLeavePersonnel();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> list1 = outExcelRecord(list);
		String fileName = "监管等级文件";
		String columnNames[] = { "编号", "姓名", "矫正单位", "目的地", "请假事由", "请假日期","被访对象","对象关系","政治面貌","工作单位","家庭地址","起始日期","截止日期","请假区域","备注" };
		String keys[] = { "id", "name", "jname", "bourn", "reason","date","target","relation","zz_status","org","address","startdate","enddate","location","remark"};
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list1, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			try {
				throw e;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return null;
	}
	/**
	 * 记录要导出的所有信息
	 *
	 * @param projects
	 * @return
	 */
	public List<Map<String, Object>> outExcelRecord(List<Map<String, Object>> projects){
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String, Object> object = null;
		for (int i = 0; i < projects.size(); i++) {
			object = projects.get(i);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", object.get("id"));
			mapValue.put("name", object.get("name"));
			mapValue.put("jname", object.get("jname"));
			mapValue.put("bourn", object.get("bourn"));
			mapValue.put("reason", object.get("reason"));
			mapValue.put("date", object.get("date"));
			mapValue.put("target", object.get("target"));
			mapValue.put("relation", object.get("relation"));
			mapValue.put("zz_status", object.get("zz_status"));
			mapValue.put("org", object.get("org"));
			mapValue.put("address", object.get("address"));
			mapValue.put("startdate", object.get("startdate"));
			mapValue.put("enddate", object.get("enddate"));
			mapValue.put("location", object.get("location"));
			mapValue.put("remark", object.get("remark"));

			listmap.add(mapValue);
		}
		return listmap;
	}
	
	
	
}
